﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Common.Logging;

namespace MailCrawler.Workflow
{
    public static class ProxyFetcher
    {
        private static readonly ILog Log = LogManager.GetCurrentClassLogger();


        public static List<Proxy> Proxies=new List<Proxy>();
        static ProxyFetcher()
        {
            var proxiStr = File.ReadAllLines("Proxies.txt");
            foreach (var s in proxiStr)
            {
                var proxiFields = s.Split(' ');

                //  pass Proxy string and bypass local machine
                Proxy loProxy = new Proxy() { Address = proxiFields[0] };
                // ** Proxy Authentication
                if (proxiFields.Length > 1)
                {
                    loProxy.Login = proxiFields[1];
                    loProxy.Password = proxiFields[0];
                }
                Proxies.Add(loProxy);
            }
            Log.Debug("Found "+Proxies.Count+" proxies");
        }
        public static WebProxy FetchRandomProxy()
        {
            if (Proxies.Count > 0)
            {
                Random rand = new Random(DateTime.Now.Millisecond);
                Proxy p = Proxies[rand.Next(Proxies.Count)];
                WebProxy proxy=new WebProxy(p.Address);
                if (p.Login.Length > 1)
                    proxy.Credentials = new NetworkCredential(p.Login,p.Password);
                
                //return Proxies[rand.Next(Proxies.Count)];
            }
            return null;
        }
        public static void Save()
        {
            var v = from a in Proxies select string.Format("{0} {1} {2}",a.Address,a.Login,a.Password);
            File.WriteAllLines("Proxies.txt", v.ToArray());
        }
    }
    public class Proxy
    {
        public string Address { get; set; }
        public string Login { get; set; }
        public string Password { get; set; }
    }
}
